//
//  DiaryCommentViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/9.
//

import Foundation
import SwiftUI

//日记评论
class DiaryCommentViewModel : BaseViewModel {
    @Published var items = [DiaryCommentBean]()
    var diaryBean: DiaryBean? = nil
    var aiRoleId: String? = nil
    @Published var scrollBottom = false
    
    override init() {
        super.init()
        self.addObserve(self, .addComment) { (selfInstance, diaryCommentBean: DiaryCommentBean) in
            if diaryCommentBean.diaryId == self.diaryBean?.objectId && diaryCommentBean.roleId == self.aiRoleId {
                selfInstance.items.append(diaryCommentBean)
                selfInstance.scrollBottom = true
            }
        }
    }
    
    func getData(_ isRefresh: Bool = false, diaryBean: DiaryBean,aiRoleId: String) {
        pageSize = 1000
        requestList(isRefresh: isRefresh) {
            var listAll = [DiaryCommentBean]()
            let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: aiRoleId)
            let text = diaryBean.getAiReply(aiRoleId: aiRoleId)
            if isRefresh && text.isEmpty == false {
                if let aiRoleBean = aiRole {
                    //更新最新数据
                    let comment = DiaryCommentBean()
                    comment.role = RoleBean.get(aiRoleBean)
                    comment.content = text
                    listAll.append(comment)
                }
            }
            var  listComment : [DiaryCommentBean] = []
            if diaryBean.isMultiple() {
                //多人回复才需要传递roleId，因为旧版本没有
                listComment = try await BackupsManager.shared.getDelegateDiary()?.queryDiaryComment(diaryId: diaryBean.objectId ?? "", aiRoleId: aiRoleId, pageNo: self.pageNo, pageSize: self.pageSize) ?? []
            } else {
                listComment = try await BackupsManager.shared.getDelegateDiary()?.queryDiaryComment(diaryId: diaryBean.objectId ?? "", pageNo: self.pageNo, pageSize: self.pageSize) ?? []
            }
            for comment in listComment {
                let aiRole = try await DiaryExt.getRole(comment)
                //由于AI会更改头像名称，所以需要根据id重新获取，在UI界面上显示最新的
                comment.role = aiRole
            }
            listAll.append(contentsOf: listComment)
            return listAll
        } suc: { comments in
            self.items.append(contentsOf: comments)
        } fail: {_ in
            showLog("报错")
        }
    }
    
    func doAddComment(text: Binding<String>) {
        request{
            let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: self.aiRoleId)
            let bean = DiaryCommentBean()
            bean.diaryId = self.diaryBean?.objectId
            bean.content = text.wrappedValue
            bean.role = RoleBean.get(userManager.user, aiRole)
            bean.roleId = aiRole?.objectId
            let nowTime = Date().timeIntervalSince1970
            bean.time  = getMillisecond(nowTime)
            try await BackupsManager.shared.getDelegateDiary()?.addDiaryComment(bean: bean)
            //更新一下日记，因为检测评论是按照更新的日记进行检测
            if let diaryBean = self.diaryBean {
                try await BackupsManager.shared.getDelegateDiary()?.saveDiary(bean: diaryBean)
            }
            return bean
        } suc: {
            //todo
            ActiveAiExt.checkComment()
            self.items.append($0)
            self.scrollBottom = true
            text.wrappedValue = ""
        } fail: {
            showToast($0.message)
        }
        
    }
    
    func doDel(index:Int) {
        let item = self.items[index]
        request{
            try check((index >= 0),"删除失败")
            try check((item.objectId?.isEmpty == false),"当前为日记回应无法删除")
            try await BackupsManager.shared.getDelegateDiary()?.deleteDiaryComment(bean: item)
        } suc: {
            withAnimation {
                self.items.remove(at: index)
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                ActiveAiExt.checkComment()
            }
            if self.items.count <= 2 {
                NotificationCenter.default.post(name: .updateComment, object: item)
            }
        } fail: {
            showTipsDialog(text: $0.message)
        }
        
    }
}
